<template>
  <el-dialog v-model="isDialogVisible" title="分配权限" width="430px" destroy-on-close>
    <el-scrollbar height="360px">
      <el-tree
        ref="menusTreeRef"
        :data="menusData"
        :props="defaultProps"
        :default-expanded-keys="defaultExpendedKeys"
        :default-checked-keys="defaultCheckedKeys"
        show-checkbox
        node-key="id"
      />
    </el-scrollbar>
    <template #footer>
      <el-button @click="handleDialogCancel">取 消</el-button>
      <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref } from 'vue'
import { useStore } from 'vuex'
import { ElTree } from 'element-plus'
import { TreeKey } from 'element-plus/lib/components/tree/src/tree.type'
import * as roleApi from '@/api/company/role'

export default defineComponent({
  name: 'PermissionDialog',
  props: {
    roleId: {
      type: Number,
      required: true
    },
    checkedKeys: {
      type: Array as PropType<TreeKey[]>,
      required: true
    }
  },
  emits: ['success'],
  setup(props, { emit }) {
    const store = useStore()
    const isDialogVisible = ref(false)
    const menusTreeRef = ref<InstanceType<typeof ElTree>>()
    const menusData = computed(() => store.getters['role/menus'])
    const defaultProps = { label: 'name' }
    const defaultExpendedKeys = computed(() => {
      // 默认展开一级菜单
      return (menusData.value as any[]).map((menu) => menu.id)
    })
    const defaultCheckedKeys = computed(() => {
      // 防止因父节点选中导致的子节点全部被选中
      // 只选中子节点，父节点自动成为半选中状态
      return props.checkedKeys.filter((key) => menusTreeRef.value?.getNode(key).isLeaf)
    })

    const visible = (isVisible = false) => {
      isDialogVisible.value = isVisible
    }

    const handleDialogCancel = () => {
      visible(false)
    }

    const handleDialogConfirm = () => {
      // 将被选中的子节点和半选中的节点合并到一起，生成完整的节点列表
      const allKeys = menusTreeRef.value
        ?.getCheckedKeys(false)
        .concat(menusTreeRef.value?.getHalfCheckedKeys())
        .sort((a, b) => (a as number) - (b as number))
      roleApi.assignPermission(props.roleId, allKeys).then(() => {
        emit('success')
        visible(false)
      })
    }

    return {
      menusTreeRef,
      isDialogVisible,
      menusData,
      defaultProps,
      defaultExpendedKeys,
      defaultCheckedKeys,
      visible,
      handleDialogCancel,
      handleDialogConfirm
    }
  }
})
</script>
